﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _13_List集合_Lambda表达式
{
    class StudentArrary
    {
        private static readonly Random _random = new Random();
        //创建一个数组，保存学生信息
        Student[] _resultStudents = null; 

        Student[] _students =
        {
            new Student("张三", "语文", _random.Next(0, 101)),
            new Student("张三", "数学", _random.Next(0, 101)),
            new Student("张三", "英语", _random.Next(0, 101)),
            new Student("李四", "语文", _random.Next(0, 101)),
            new Student("李四", "数学", _random.Next(0, 101)),
            new Student("李四", "英语", _random.Next(0, 101)),
            new Student("王五", "语文", _random.Next(0, 101)),
            new Student("王五", "数学", _random.Next(0, 101)),
            new Student("王五", "英语", _random.Next(0, 101))
        };

        //找出所有考试成绩低于60分的学生
        public void ForEach(Action<Student> action)
        {
            foreach (var item in _students)
            {
                action(item);
            }
        }

        //创一个方法Where，找出所有名为语文所有考试成绩，保存到一个新的数组中
        public StudentArrary Where(Func<Student,bool> func)
        {
            //获取符合条件的学生个数，为_resultStudents 数组开辟空间
            int count = 0;
            foreach (var student in _students)
            {
                if (func(student))
                {
                    count++;
                }
            }
            //创建对应的数组长度
            _resultStudents = new Student[count];
            //将符合条件的学生保存到数组中
            int index = 0;
            foreach (var student in _students)
            {
                if (func(student))
                {
                    _resultStudents[index] = student;
                    index++;
                }
            }

            return this;
        }

        //创建一个方法用于求为_resultStudents的平均分
        public double Average()
        {
            int sum = 0;
            foreach (var student in _resultStudents)
            {
                sum += student.Score;
            }
            return sum * 1.0 / _resultStudents.Length;

        }
     }
}
